//
//  ZLFNetWorkTool.swift
//  Swift_Example
//
//  Created by zluof on 16/12/24.
//  Copyright © 2016年 zluof. All rights reserved.
//

import UIKit
import Alamofire

class ZLFNetWorkTool: NSObject {

    func request(requestNumber: Int ,requestType: requestType,parameters:[String : AnyObject]?,complete:@escaping (_ result: AnyObject?,_ error:NSError?) -> ()) {
        let requestBack = {(respondsResult : DataResponse<Any>) in

            if respondsResult.result.isSuccess {
                complete(respondsResult.result.value as AnyObject?,nil)
            }else{
                complete(nil,respondsResult.result.error as NSError?)
            }
            
        }
        let url = BaseUrl + "&requestData=%" + md5(md5String: "")
        
        let httpMethod: HTTPMethod = requestType == .getRequest ? .get : .post
        request(url, method: httpMethod, parameters: parameters, encoding: URLEncoding.default, headers:nil).responseJSON(completionHandler: requestBack)
       
    }
}
extension ZLFNetWorkTool{
    //MD5 加密
    
    
    func md5(md5String:String) -> String {
        let str = md5String.cString(using: String.Encoding.utf8)
        let strLen = CUnsignedInt(md5String.lengthOfBytes(using: String.Encoding.utf8))
        let digestLen = Int(CC_MD5_DIGEST_LENGTH)
        let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
        CC_MD5(str!, strLen, result)
        let hash = NSMutableString()
        for i in 0 ..< digestLen {
            hash.appendFormat("%02x", result[i])
        }
        result.deinitialize()
        
        return String(format: hash as String)
    }
    
    //JSON
    func jsonString(url:String,parma:[String : Any] ) -> String {
        let user = UserDefaults.standard.object(forKey: "")
        var user_id = ""
        
        if (user as! String).isEmpty {
            user_id = user as! String
        }
        let time_number = getCurrentDate()
        
        let deviceId = UIDevice.current.identifierForVendor?.uuidString
        
        let tokeString = url + user_id + time_number + NetKey
        
        let md5string = md5(md5String: tokeString )
        
        let dictParem : [String :AnyObject?] = ["pack_no":url as Optional<AnyObject>,
                                            "date":time_number as Optional<AnyObject>,
                                            "user_id":user_id as Optional<AnyObject>,
                                            "deviceId":deviceId! as Optional<AnyObject>,
                                            "token":md5string as Optional<AnyObject>,
                                            "data":parma as Optional<AnyObject>]
        
        
        var string  = String()
        do{

            let json = try JSONSerialization.data(withJSONObject: dictParem, options: .prettyPrinted)
            string = String(data: json, encoding:.utf8)!
            
        } catch {
            NSLog("JSON解析失败")
        }
        
        return string
        
        
        
        
    }
    
    func getCurrentDate() -> String {
        let date = Date.init(timeIntervalSinceNow: 0);
        let add_time : TimeInterval = date.timeIntervalSince1970 * 1000
        let time:String = String(add_time)
        return time.appendingFormat(time, ".0f")
    }
}
enum requestType {
    case getRequest
    case postRequest
}
